<template>
    <div class="madp-code-list-wrap">
        <div class="madp-code-title">全部渠道码（{{ codeTotalNum }}）</div>
        <div class="madp-channel-code-container">
            <div class="madp-container-left">
                <el-input v-model.trim="keyword" placeholder="请输入渠道码名称" @keyup.enter.native="fetchCodeList" @clear="setShowGroupStatus" clearable>
                    <i slot="suffix" class="el-icon-search" @click="fetchCodeList"></i>
                </el-input>
                <div class="madp-code-group-list" v-if="showGroupWrap">
                    <div class="madp-group-wrap" v-for="(groupItem, index) in codeGroupList" :key="groupItem.groupId">
                        <div class="madp-info-wrap">
                            <div class="madp-info-left">
                                <!-- isFold 是否折叠 -->
                                <i class="el-icon-caret-right madp-fold-icon" v-if="groupItem.isFold && groupItem.count > 0" @click="changeFoldStatus(groupItem)"></i>
                                <i class="el-icon-caret-bottom madp-fold-icon" v-if="!groupItem.isFold && groupItem.count > 0" @click="changeFoldStatus(groupItem)"></i>
                                <div
                                    class="madp-name-wrap"
                                    :class="{
                                        'madp-no-children': groupItem.count < 1
                                    }"
                                >
                                    <img class="madp-folder-icon" src="/img/folder.png" />
                                    <span class="madp-group-name"> {{ groupItem.groupName }}（{{ groupItem.count || 0 }}） </span>
                                </div>
                            </div>
                            <div class="madp-info-right">
                                <el-checkbox
                                    class="madp-checkbox"
                                    v-model="groupItem.isChecked"
                                    @change="
                                        (e) =>
                                            formatSelectList({
                                                ...groupItem,
                                                type: 1,
                                                index
                                            })
                                    "
                                    :disabled="groupItem.isDisabled || groupItem.count === 0"
                                ></el-checkbox>
                            </div>
                        </div>
                        <div v-if="!groupItem.isFold">
                            <div class="madp-info-wrap" v-for="(codeItem, ind) in groupItem.channelCodeListCCVOList" :key="codeItem.channelId">
                                <div class="madp-info-left madp-code-item-left">
                                    <div :class="['madp-name-wrap', codeItem.isDisabled ? 'madp-text-gray' : '']">
                                        <span class="madp-group-name">
                                            {{ codeItem.channelName }}
                                        </span>
                                    </div>
                                </div>
                                <div class="madp-info-right">
                                    <el-checkbox
                                        class="madp-checkbox"
                                        v-model="codeItem.isChecked"
                                        @change="
                                            (e) =>
                                                formatSelectList({
                                                    ...codeItem,
                                                    type: 2,
                                                    groupId: groupItem.groupId,
                                                    index,
                                                    ind
                                                })
                                        "
                                        :disabled="codeItem.isDisabled"
                                    ></el-checkbox>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="madp-code-group-list" v-else>
                    <div class="madp-info-wrap" v-for="codeItem in searchCodeList" :key="codeItem.channelId">
                        <div class="madp-info-left">
                            <div :class="['madp-name-wrap', codeItem.isDisabled ? 'madp-text-gray' : '']">
                                <span class="madp-group-name">
                                    {{ codeItem.channelName }}
                                </span>
                            </div>
                        </div>
                        <div class="madp-info-right">
                            <el-checkbox
                                class="madp-checkbox"
                                v-model="codeItem.isChecked"
                                @change="
                                    (e) =>
                                        formatSelectList({
                                            ...codeItem,
                                            type: 2
                                        })
                                "
                                :disabled="codeItem.isDisabled"
                            ></el-checkbox>
                        </div>
                    </div>
                </div>
            </div>
            <div class="madp-container-right">
                <div class="madp-code-title">已选择分组和渠道码（{{ selectGroupAndCodeList.length }}）</div>
                <div class="madp-code-group-list">
                    <div class="madp-info-wrap" v-for="item in selectGroupAndCodeList" :key="item.id">
                        <div class="madp-info-left">
                            <div class="madp-name-wrap">
                                <img class="madp-folder-icon" src="/img/folder.png" v-if="item.type === 1" />
                                <span class="madp-group-name">
                                    {{ item.name }}
                                </span>
                            </div>
                        </div>
                        <div class="madp-info-right">
                            <i class="el-icon-close" @click="deleteCodeOrGroupItem(item)"></i>
                        </div>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer madp-select-btn-group">
                    <el-button @click="closeSelectDialog">取消</el-button>
                    <el-button type="primary" @click="confirmSelectCode">确定</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { queryGroupAndCode } from '@/api/customers-of-drainage/customers-of-drainage';
export default {
    props: {
        defaultGroupAndCodeList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        defaultGroupAndCodeIds: {
            type: Array,
            default: () => {
                return [];
            }
        },
        defaultCodeIds: {
            type: Array,
            default: () => {
                return [];
            }
        },
        defaultGroupIds: {
            type: Array,
            default: () => {
                return [];
            }
        },
        selectType: {
            type: String,
            default: 'collect'
        }
    },
    data() {
        return {
            // 输入内容
            keyword: '',
            // 视图显示条件
            showGroupWrap: true,
            // 渠道活码分组数据
            codeGroupList: [],
            // 活码数据
            codeList: [],
            codeListTwo: [],
            searchCodeList: [],
            selectGroupAndCodeList: [],
            codeTotalNum: 0,
            selectGroupIds: [],
            selectCodeIds: []
        };
    },
    created() {
        this.selectGroupAndCodeList = JSON.parse(JSON.stringify(this.defaultGroupAndCodeList));
        this.selectCodeIds = JSON.parse(JSON.stringify(this.defaultCodeIds));
        this.selectGroupIds = JSON.parse(JSON.stringify(this.defaultGroupIds));
        // this.initData()
        this.getGroupAndCode();
    },
    methods: {
        // 获取分组和活码
        getGroupAndCode() {
            queryGroupAndCode().then((res) => {
                if (res.data.code === 0) {
                    const newData = res.data.data || [];
                    let isHaveFold = undefined;
                    let total = 0;
                    newData.forEach((item) => {
                        if (this.selectGroupIds.includes(item.groupId)) {
                            item.isChecked = true;
                        }
                        item.channelCodeListCCVOList.forEach((it) => {
                            if (this.selectCodeIds.includes(it.channelId)) {
                                it.isChecked = true;
                            }
                        });
                    });
                    this.codeGroupList = newData.map((item, index) => {
                        total += item.count;
                        if (isHaveFold === undefined && item.count > 0) {
                            isHaveFold = index;
                        }
                        return {
                            ...item,
                            isFold: index !== isHaveFold
                        };
                    });
                    this.codeTotalNum = total;
                    this.setGroupOrCodeDisabled();
                }
            });
        },
        // 关闭弹窗
        closeSelectDialog() {
            this.$emit('closeSelectDialog');
        },
        // 点击确定
        confirmSelectCode() {
            const codeGroupName = this.selectGroupAndCodeList.map((item) => item.name).toString();
            this.$emit('confirmSelectCode', {
                selectCodeIds: this.selectCodeIds,
                selectGroupIds: this.selectGroupIds,
                selectGroupAndCodeList: this.selectGroupAndCodeList,
                codeGroupName
            });
        },
        // 更新折叠状态
        changeFoldStatus(groupItem) {
            groupItem.isFold = !groupItem.isFold;
        },
        // 输入框清空 默认显示分组结构
        setShowGroupStatus() {
            this.showGroupWrap = true;
            this.getGroupAndCode();
        },
        // 输入框回车键后获取codeList
        fetchCodeList() {
            if (!this.keyword) {
                this.showGroupWrap = true;
                this.getGroupAndCode();
                return;
            }
            this.showGroupWrap = false;
            queryGroupAndCode({ keyWords: this.keyword }).then((res) => {
                if (res.data.code === 0) {
                    const data = res.data.data || [];
                    const newData = [];
                    const isDisabled = this.selectGroupAndCodeList.length >= 5;
                    data.forEach((item) => {
                        newData.push(...JSON.parse(JSON.stringify(item.channelCodeListCCVOList)));
                    });
                    newData.forEach((item) => {
                        if (this.selectCodeIds.includes(item.channelId)) {
                            item.isChecked = true;
                            item.isDisabled = isDisabled;
                        }
                    });
                    this.searchCodeList = newData;
                }
            });
        },
        // 已选择列表数据处理
        formatSelectList(itemData) {
            let { type, isChecked } = itemData;
            if (isChecked) {
                if (type === 1) {
                    this.selectGroupIds.push(itemData.groupId);
                    this.selectGroupAndCodeList.push({
                        ...itemData,
                        name: itemData.groupName,
                        id: itemData.groupId + 'group'
                    });
                } else {
                    this.selectCodeIds.push(itemData.channelId);
                    this.selectGroupAndCodeList.push({
                        ...itemData,
                        name: itemData.channelName,
                        id: itemData.channelId + 'code'
                    });
                }
            } else {
                if (type === 1) {
                    let extIndex = this.selectGroupIds.indexOf(itemData.groupId);
                    this.selectGroupIds.splice(extIndex, 1);
                    this.selectGroupAndCodeList = this.selectGroupAndCodeList.filter((item) => itemData.groupId + 'group' !== item.id);
                } else {
                    let extIndex = this.selectCodeIds.indexOf(itemData.channelId);
                    this.selectCodeIds.splice(extIndex, 1);
                    this.selectGroupAndCodeList = this.selectGroupAndCodeList.filter((item) => itemData.channelId + 'code' !== item.id);
                }
            }

            if (this.selectType === 'compare') {
                this.setGroupOrCodeDisabled();
            }
            this.$forceUpdate();
        },
        // 已选择列表已有5个后其余选项disabled
        setGroupOrCodeDisabled() {
            if (this.selectGroupAndCodeList.length === 5 || this.selectGroupAndCodeList.length > 5) {
                this.codeGroupList.forEach((item) => {
                    if (!item.isChecked) {
                        item.isDisabled = true;
                    } else {
                        item.isDisabled = false;
                    }
                    item.channelCodeListCCVOList.forEach((it) => {
                        if (!it.isChecked) {
                            it.isDisabled = true;
                        } else {
                            it.isDisabled = false;
                        }
                    });
                });

                this.setSearchCodeList(true);
            } else {
                this.codeGroupList.forEach((item) => {
                    item.isDisabled = false;
                    item.channelCodeListCCVOList.forEach((it) => {
                        it.isDisabled = false;
                    });
                });

                this.setSearchCodeList(false);
            }
        },
        // 配置数据
        setSearchCodeList(isDisabled) {
            this.searchCodeList.forEach((item) => {
                item.isDisabled = isDisabled;
            });
        },
        // 删除分组
        deleteCodeOrGroupItem(itemData) {
            itemData.isChecked = false;
            if (itemData.type === 1 && itemData.index !== undefined) {
                this.codeGroupList[itemData.index].isChecked = false;
            } else {
                if (itemData.index !== undefined && itemData.ind !== undefined) {
                    this.codeGroupList[itemData.index].channelCodeListCCVOList[itemData.ind].isChecked = false;
                } else {
                    this.codeGroupList.forEach((item) => {
                        item.channelCodeListCCVOList.forEach((it) => {
                            if (it.channelId === itemData.channelId) {
                                it.isChecked = false;
                            }
                        });
                    });
                }
                if (!this.showGroupWrap) {
                    this.searchCodeList.forEach((item) => {
                        if (item.channelId === itemData.channelId) {
                            item.isChecked = false;
                        }
                    });
                }
            }

            this.formatSelectList(itemData);
        }
    }
};
</script>
<style lang="scss" scoped>
.madp-code-list-wrap {
    margin-top: 10px;
    height: 440px;
    overflow: auto;
    display: flex;
    flex-direction: column;
    .madp-channel-code-container {
        display: flex;
        margin-top: 10px;
        flex: 1;
        .madp-container-left {
            width: 323px;
            border-right: 1px solid #e8e8e8;
            .el-input {
                width: 270px;
            }
            /deep/ .el-input__suffix {
                display: flex;
                align-items: center;
                .el-input__suffix-inner {
                    display: flex;
                    justify-content: flex-end;
                    flex-direction: row-reverse;
                    align-items: center;
                    .el-input__clear {
                        position: absolute;
                        right: 20px;
                        top: 0;
                    }
                }
            }
        }
        .madp-container-right {
            flex: 1;
            padding-left: 40px;
            position: relative;
            display: flex;
            flex-direction: column;
        }
        .madp-code-group-list {
            margin-top: 10px;
            .madp-group-wrap {
                margin-bottom: 10px;
            }
            .madp-info-wrap {
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 270px;
                margin-bottom: 10px;
                .madp-info-left {
                    display: flex;
                    align-items: center;
                    .madp-fold-icon {
                        color: #1890ff;
                    }
                    .madp-name-wrap {
                        display: flex;
                        align-items: center;
                        .madp-folder-icon {
                            width: 18px;
                            margin-right: 4px;
                        }
                    }
                    .madp-text-gray {
                        color: rgba(0, 0, 0, 0.25);
                    }
                }
                .madp-code-item-left {
                    padding-left: 36px;
                }
                .madp-info-right {
                    /deep/ .madp-checkbox.el-checkbox .el-checkbox__input .el-checkbox__inner {
                        width: 16px;
                        height: 16px;
                        border-radius: 50%;
                    }
                }
            }
        }
        .madp-select-btn-group {
            align-self: flex-end;
            position: absolute;
            bottom: 0;
        }
    }
}
.madp-no-children {
    color: #999999;
}
</style>
